package com.example.pkmedical;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextClock;
import android.widget.TextView;

import androidx.fragment.app.FragmentTransaction;

import com.example.pkmedical.APP.MyApp;
import com.example.pkmedical.Activity.LockScreenActivity;
import com.example.pkmedical.Activity.chairposition.ChairPositionOne;
import com.example.pkmedical.Activity.help.HelpActivity;
import com.example.pkmedical.Activity.rollovershock.RolloverShockNextActivity;
import com.example.pkmedical.Activity.usermsg.UserMessageActivity;
import com.example.pkmedical.Activity.warning.CrushionWarningActivity;
import com.example.pkmedical.Activity.warning.HeadBloodWarningActivity;
import com.example.pkmedical.Base.BaseActivity;
import com.example.pkmedical.DB.WeightData;
import com.example.pkmedical.Event.MessageWrap;
import com.example.pkmedical.Fragments.FbzlFragment;
import com.example.pkmedical.Fragments.HomeFragment;
import com.example.pkmedical.Fragments.RemindFragment;
import com.example.pkmedical.Fragments.RoutineFragment;
import com.example.pkmedical.Fragments.SettingFragment;
import com.example.pkmedical.Fragments.UserMsgFragment;
import com.example.pkmedical.Fragments.WarningFragment;
import com.example.pkmedical.Fragments.WeighFragment;
import com.example.pkmedical.Utils.CommandUtil;
import com.example.pkmedical.Utils.DistinguishUtil;
import com.example.pkmedical.Utils.EventBusUtils;
import com.example.pkmedical.Utils.FinishActivityManager;
import com.example.pkmedical.Utils.IoTimer;
import com.example.pkmedical.Utils.SPUtils;
import com.example.pkmedical.Utils.SerialProtUtil;
import com.kongqw.serialportlibrary.listener.OnSerialPortDataListener;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.ModelAdapter;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.example.pkmedical.Activity.warning.HeadBloodWarningActivity.mHeadBloodTimeCountDisposable;
import static com.example.pkmedical.Utils.CommandUtil.IS_100_AIR;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.main_house)
    ImageView mainHouse;
    @BindView(R.id.main_house_text)
    TextView mainHouseText;
    @BindView(R.id.main_date)
    TextClock mainDate;
    @BindView(R.id.id_main_bottom_sy)
    RadioButton idMainBottomSy;
    @BindView(R.id.id_main_bottom_fbzl)
    RadioButton idMainBottomFbzl;
    @BindView(R.id.id_main_bottom_cg)
    RadioButton idMainBottomCg;
    @BindView(R.id.id_main_bottom_cz)
    RadioButton idMainBottomCz;
    @BindView(R.id.id_main_bottom_yj)
    RadioButton idMainBottomYj;
    @BindView(R.id.id_main_bottom_tx)
    RadioButton idMainBottomTx;
    @BindView(R.id.id_main_bottom_sz)
    RadioButton idMainBottomSz;
    @BindView(R.id.id_main_bottom_user)
    RadioButton idMainBottomUser;
    @BindView(R.id.main_radio_group)
    RadioGroup mainRadioGroup;
    @BindView(R.id.id_main_bottom_sp)
    ImageView idMainBottomSp;
    @BindView(R.id.id_main_bottom_help)
    ImageView idMainBottomHelp;
    @BindView(R.id.iv_bottom_left)
    ImageView ivBottomLeft;
    @BindView(R.id.iv_bottom_right)
    ImageView ivBottomRight;
    @BindView(R.id.home_scrollview)
    HorizontalScrollView homeScrollview;

    HomeFragment homeFragment;
    WarningFragment warningFragment;
    WeighFragment weighFragment;
    FbzlFragment fbzlFragment;
    SettingFragment settingFragment;
    RoutineFragment routineFragment;
    RemindFragment remindFragment;
    UserMsgFragment userMsgFragment;
    private static final String TAG = "yangshuo";
    private boolean isCushionHave = true;
    private boolean isFirst = true;
    private boolean isCrushion = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        SerialProtUtil.getInstance().openSerialPort();
        idMainBottomCg.setChecked(true);
        idMainBottomSy.setChecked(true);
    }

    @Override
    public void initData() {

        SerialProtUtil.getInstance().setOnSerialPortDataListener(new OnSerialPortDataListener() {
            @Override
            public void onDataReceived(byte[] bytes) {
                Log.d(TAG, "onDataReceived [ byte[] ]: " + Arrays.toString(bytes));

                if (DistinguishUtil.distinguishUtil(bytes)) {
                    switch (bytes[2]) {
                        case 0x03:
                            EventBusUtils.post(MessageWrap.getInstance(MessageWrap.QIDIANMOSHI, bytes));
                            break;
                        case 0x05:
                            EventBusUtils.post(MessageWrap.getInstance(MessageWrap.SHUSHIMOSHI, bytes));
                            break;
                        case 0x06:
                            EventBusUtils.post(MessageWrap.getInstance(MessageWrap.ROLLOVERIMG, bytes));
                            break;
                        case 0x07:
                            EventBusUtils.post(MessageWrap.getInstance(MessageWrap.CALIBRATION_WEIGHT, bytes));
                            break;
                        case 0x08:
                            EventBusUtils.post(MessageWrap.getInstance(MessageWrap.SENSOR_WEIGHT, bytes));
                            break;
                        case 0x09:
                            EventBusUtils.post(MessageWrap.getInstance(MessageWrap.WEIGHT_SHOW, bytes));
                            break;
                        case 0x0a:
                            EventBusUtils.post(MessageWrap.getInstance(MessageWrap.WEIGHT_ZERO, bytes));
                            break;
                        case 0x0b:
                            EventBusUtils.post(MessageWrap.getInstance(MessageWrap.WEIGHT_SHOW_ADD, bytes));
                            break;
                        case 0x0c:
                            EventBusUtils.post(MessageWrap.getInstance(MessageWrap.RAIL_STATE, bytes));

                            break;
                        case 0x0d:
                            if (bytes.length > 3) {
                                if (0x01 == bytes[3]) {
                                    Log.d(TAG, "onDataReceived [ byte[] ]:JumpToPositionChange");
                                    startActivity(new Intent(MyApp.getAppContext(), ChairPositionOne.class));
                                    FinishActivityManager.getManager().finishActivity(RolloverShockNextActivity.class);
                                    SerialProtUtil.getInstance().sendBytes(2, CommandUtil.STOP_ALL_GO_CHAIR);
                                    SerialProtUtil.getInstance().sendBytes50(2, CommandUtil.OUT_HELP);
                                    SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.OUT_ZDCQ);
                                    Log.d("yangshuo", "first!!!!!!!!!!!!!!!!!!");
                                    EventBusUtils.post(MessageWrap.getInstance(MessageWrap.CHAIR_POSITION, bytes));

                                }
//                                else if (bytes.length == 3) {
//                                    startActivity(new Intent(MyApp.getAppContext(), ChairPositionOne.class));
//                                    EventBusUtils.post(MessageWrap.getInstance(MessageWrap.CHAIR_POSITION, bytes));
//                                }
                                else {
                                    EventBusUtils.post(MessageWrap.getInstance(MessageWrap.CHAIR_POSITION, bytes));
                                }
                            }
                            break;

                        case 0x0e:
                            FinishActivityManager.getManager().finishActivity(ChairPositionOne.class);
                            SerialProtUtil.getInstance().sendBytes(2, CommandUtil.STOP_ALL_GO_CHAIR);
                            break;
                        case 0x0f://50KG临界充气
                            if (isCushionHave && IS_100_AIR) {
                                switch (bytes[3]) {
                                    case 0x01:
                                        SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.INFILATION);
                                        break;
                                    case 0x02:
                                        SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.NO_INFILATION);
                                        break;
                                }
                            }


                            break;
                        case 0x10://接收确认在线
                            SerialProtUtil.getInstance().sendBytes50(2, CommandUtil.APP_STARTED);
                            break;
                        case 0x11://气垫是否在线
                            Log.d("yangshuoisCushion", bytes[3] + "-------------");
                            switch (bytes[3]) {
                                case 0x01:
                                    if (!CommandUtil.CRUSHI_TYPE) {
                                        FinishActivityManager.getManager().finishActivity(CrushionWarningActivity.class);
                                    }
                                    CommandUtil.CRUSHI_TYPE = true;
                                    isCushionHave = true;
                                    SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.CHANGGUI_TTYPE);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            idMainBottomCg.setVisibility(View.VISIBLE);
                                            idMainBottomFbzl.setVisibility(View.VISIBLE);
                                            startActivity(new Intent(MyApp.getAppContext(), CrushionWarningActivity.class));
                                        }
                                    });
                                    break;
                                case 0x02:
                                    if (CommandUtil.CRUSHI_TYPE) {
                                        FinishActivityManager.getManager().finishActivity(CrushionWarningActivity.class);
                                    }
                                    CommandUtil.CRUSHI_TYPE = false;
                                    isCushionHave = false;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            idMainBottomCg.setVisibility(View.GONE);
                                            idMainBottomFbzl.setVisibility(View.GONE);
                                            idMainBottomSy.setChecked(true);
                                            startActivity(new Intent(MyApp.getAppContext(), CrushionWarningActivity.class));
                                            FinishActivityManager.getManager().finishActivity(RolloverShockNextActivity.class);
                                            if (CommandUtil.IS_ROLLOVEW_SHOCK) {

                                                SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.CEFAN_STOP);
                                            }
                                            FinishActivityManager.getManager().finishActivity(ChairPositionOne.class);

                                        }
                                    });
                                    break;
                                case 0x03:
                                    CommandUtil.CRUSHI_TYPE = true;
                                    isCushionHave = true;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            idMainBottomCg.setVisibility(View.VISIBLE);
                                            idMainBottomFbzl.setVisibility(View.VISIBLE);
                                        }
                                    });
                                    break;
                                case 0x04:
                                    isCushionHave = false;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            idMainBottomCg.setVisibility(View.GONE);
                                            idMainBottomFbzl.setVisibility(View.GONE);
                                            startActivity(new Intent(MyApp.getAppContext(), CrushionWarningActivity.class));
                                        }
                                    });

                                    break;
                            }
                            break;
                        case 0x12:
                            switch (bytes[3]) {
                                case 0x01:
                                    CommandUtil.DEFAULT_HEAD_TYPE = 1;
                                    break;
                                case 0x02:
                                    CommandUtil.DEFAULT_HEAD_TYPE = 2;
                                    break;
                                case 0x03:
                                    CommandUtil.DEFAULT_HEAD_TYPE = 3;
                                    break;
                                case 0x04:
                                    CommandUtil.DEFAULT_HEAD_TYPE = 4;
                                    break;
                            }
                            if (CommandUtil.IN_HEADBLOOD) {
                                EventBusUtils.post(MessageWrap.getInstance(MessageWrap.WARNING_CODE, bytes));
                            } else {
                                startActivity(new Intent(MyApp.getAppContext(), HeadBloodWarningActivity.class));
                                EventBusUtils.post(MessageWrap.getInstance(MessageWrap.WARNING_CODE, bytes));
                            }
                            break;
                        case 0x13:
                            if (mHeadBloodTimeCountDisposable != null) {
                                mHeadBloodTimeCountDisposable.dispose();
                            }
                            if (CommandUtil.IN_HEADBLOOD) {
                                FinishActivityManager.getManager().finishActivity(HeadBloodWarningActivity.class);
                            }
                            break;

                        case 0x14:
                            if (mHeadBloodTimeCountDisposable != null) {
                                mHeadBloodTimeCountDisposable.dispose();
                            }
                            break;
                        case 0x15:
                            switch (bytes[3]) {
                                case 0x01:
                                    SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.QIANQING_0);
                                    break;
                                case 0x02:
                                    SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.HOUQING_0);
                                    break;
                                case 0x03:
                                    SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.BOOST_0);
                                    break;
                            }

                            break;
                    }
                }
//                else {
//                    if (bytes[0] == 1 && bytes[1] == 1){
//                        CommandUtil.IS_CAN_REQUEST = true;
//                    }else {
//                        CommandUtil.IS_CAN_REQUEST = false;
//                    }
//                }
            }

            @Override
            public void onDataSent(byte[] bytes) {
                Log.d(TAG, "onDataSent [ byte[] ]: " + Arrays.toString(bytes));
//                Log.d(TAG, "onDataSent [ String ]: " + new String(bytes));
            }
        });
    }

    @Override
    public void initView() {
        mainRadioGroup.setOnCheckedChangeListener(this);
        mainHouse.setImageResource(R.drawable.img_home_title_house);
        mainHouseText.setText(R.string.主屏幕);
        homeScrollview.setSmoothScrollingEnabled(true);
        goDefult();

    }

    private void goDefult() {
        CommandUtil.LEAVEBED_TYPE = 0;
        CommandUtil.HEAD_WARNING_TYPE = 0;
        SPUtils.getInstance().put("bed_final_angle", 0);
        SPUtils.getInstance().put("user_height", "不适用");
        SPUtils.getInstance().put("user_first_weight", getString(R.string.weight_device_no_apply));
        SPUtils.getInstance().put("user_last_weight", getString(R.string.weight_device_no_apply));
        SPUtils.getInstance().put("user_now_weight", getString(R.string.weight_device_no_apply));
        SPUtils.getInstance().put("user_difference_weight_all", "0");
        SPUtils.getInstance().put("comfortable_FootNum", CommandUtil.CHANGGUI_HEAD);
        SPUtils.getInstance().put("comfortable_HipNum", CommandUtil.CHANGGUI_HIP);
        SPUtils.getInstance().put("comfortable_HeadNum", CommandUtil.CHANGGUI_FOOT);
        SPUtils.getInstance().put("rollover_left_minute", CommandUtil.ROLLOVER_LEFT_TIME);
        SPUtils.getInstance().put("rollover_ping_minute", CommandUtil.ROLLOVER_PING_TIME);
        SPUtils.getInstance().put("rollover_right_minute", CommandUtil.ROLLOVER_RIGHT_TIME);
        SPUtils.getInstance().put("rollover_left_bfb", CommandUtil.ROLLOVER_LEFT_NUM);
        SPUtils.getInstance().put("rollover_right_bfb", CommandUtil.ROLLOVER_RIGHT_NUM);
        SPUtils.getInstance().put("shock_qiangdu_qiaoji", CommandUtil.SHOCK_QIAOJI_STRENGTH);
        SPUtils.getInstance().put("shock_qiangdu_zhendong", CommandUtil.SHOCK_ZHENDONG_STRENGTH);
        SPUtils.getInstance().put("shock_time_qiaoji", CommandUtil.SHOCK_QIAOJI_TIME);
        SPUtils.getInstance().put("shock_time_zhendong", CommandUtil.SHOCK_ZHENDONG_TIME);
        SPUtils.getInstance().put("TOZERO_DATA", CommandUtil.TOZERO_DEFAULT_TIME);
        SPUtils.getInstance().put("NEWUSER_ZERO_DATA", CommandUtil.TOZERO_DEFAULT_TIME);
        SPUtils.getInstance().put("Initial_time", CommandUtil.TOZERO_DEFAULT_TIME);
        SPUtils.getInstance().put("Last_time", CommandUtil.TOZERO_DEFAULT_TIME);


        WeightData weightData = new WeightData();
        ModelAdapter<WeightData> adapter = FlowManager.getModelAdapter(WeightData.class);
        List<WeightData> list = SQLite.select().from(WeightData.class).queryList();
        if (list.size()==0){
        for (int i = 0; i < 6; i++) {
            weightData.id = i;//这一行必须加，必须指定id，后面才能根据id修改某一条的数据
            weightData.date = "12/20 00:00";
            weightData.weight = Float.parseFloat("0");
            adapter.insert(weightData);//插入
        }
        }

    }

    @Override
    public void initPresenter() {
        requestPermission(new String[]{"android.permission.SET_TIME"});
    }

    @Override
    public void showDialog(String... msg) {

    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(MessageWrap event) {
        super.onReceiveEvent(event);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        switch (checkedId) {
            case R.id.id_main_bottom_sy:
                mainHouse.setImageResource(R.drawable.img_home_title_house);
                mainHouseText.setText(R.string.title_home);
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.main_framelayout, homeFragment);
                } else {
                    transaction.show(homeFragment);
                }
                break;
            case R.id.id_main_bottom_fbzl:
                isCrushion = false;
                if (isCushionHave) {
                    mainHouse.setImageResource(R.drawable.img_title_fbzl);
                    mainHouseText.setText(R.string.title_fbzl);
                    if (fbzlFragment == null) {
                        fbzlFragment = new FbzlFragment();
                        transaction.add(R.id.main_framelayout, fbzlFragment);
                    } else {
                        transaction.show(fbzlFragment);
                    }
                }
                break;
            case R.id.id_main_bottom_yj:
                mainHouse.setImageResource(R.drawable.img_title_warning);
                mainHouseText.setText(R.string.title_warning);
                if (warningFragment == null) {
                    warningFragment = new WarningFragment();
                    transaction.add(R.id.main_framelayout, warningFragment);
                } else {
                    transaction.show(warningFragment);
                }
                break;
            case R.id.id_main_bottom_cz:
                mainHouseText.setText(R.string.title_weight);
                mainHouse.setImageResource(R.drawable.img_title_weight);
                if (weighFragment == null) {
                    weighFragment = new WeighFragment();
                    transaction.add(R.id.main_framelayout, weighFragment);
                } else {
                    transaction.show(weighFragment);
                }
                break;
            case R.id.id_main_bottom_sz:
                mainHouse.setImageResource(R.drawable.img_title_sz);
                mainHouseText.setText(R.string.title_routine);
                if (settingFragment == null) {
                    settingFragment = new SettingFragment();
                    transaction.add(R.id.main_framelayout, settingFragment);
                } else {
                    transaction.show(settingFragment);
                }
                break;
            case R.id.id_main_bottom_cg:
                isCrushion = false;
                if (isCushionHave) {
                    mainHouse.setImageResource(R.drawable.img_title_qdms);
                    mainHouseText.setText(R.string.title_qdms);
                    if (routineFragment == null) {
                        routineFragment = new RoutineFragment();
                        transaction.add(R.id.main_framelayout, routineFragment);
                    } else {
                        transaction.show(routineFragment);
                    }
                }

                break;
            case R.id.id_main_bottom_tx:
                mainHouse.setImageResource(R.drawable.img_title_remindx);
                mainHouseText.setText(R.string.title_remind);
                if (remindFragment == null) {
                    remindFragment = new RemindFragment();
                    transaction.add(R.id.main_framelayout, remindFragment);
                } else {
                    transaction.show(remindFragment);
                }
                break;
            case R.id.id_main_bottom_user:
                mainHouse.setImageResource(R.drawable.img_title_usermsg);
                mainHouseText.setText(R.string.title_user);
                if (userMsgFragment == null) {
                    userMsgFragment = new UserMsgFragment();
                    transaction.add(R.id.main_framelayout, userMsgFragment);
                } else {
                    transaction.show(userMsgFragment);
                }
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    public void hideAllFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (warningFragment != null) {
            transaction.hide(warningFragment);
        }
        if (weighFragment != null) {
            transaction.hide(weighFragment);
        }
        if (fbzlFragment != null) {
            transaction.hide(fbzlFragment);
        }
        if (settingFragment != null) {
            transaction.hide(settingFragment);
        }
        if (routineFragment != null) {
            transaction.hide(routineFragment);
        }
        if (remindFragment != null) {
            transaction.hide(remindFragment);
        }
        if (userMsgFragment != null) {
            transaction.hide(userMsgFragment);
        }
    }

    @OnClick({R.id.iv_bottom_left, R.id.iv_bottom_right, R.id.id_main_bottom_sp, R.id.id_main_bottom_help})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_bottom_left:
                homeScrollview.smoothScrollTo(0, 0);
                break;
            case R.id.iv_bottom_right:
                homeScrollview.smoothScrollTo(homeScrollview.getMaxScrollAmount(), 0);
                break;
            case R.id.id_main_bottom_sp:
                startActivity(new Intent(this, LockScreenActivity.class));
//                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                break;
            case R.id.id_main_bottom_help:
                startActivity(new Intent(this, UserMessageActivity.class));
//                startActivity(new Intent(this, HelpActivity.class));
//                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                break;
        }
    }

    private int timeLong = 15;
    private Disposable mTimeCountDisposable;

    /**
     * 倒计时
     */
    public void TimeCount() {
        if (mTimeCountDisposable != null) {
            //取消上一次的订阅
            mTimeCountDisposable.dispose();
        }
//        //0-count依次输出，延时0s执行，每1s发射一次。
        mTimeCountDisposable = Flowable.intervalRange(0,


                15, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {
                    timeLong -= 1;
                })
                .doOnComplete(() -> {
                    if (mTimeCountDisposable != null) {
                        mTimeCountDisposable.dispose();
                    }
                    SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.QIANQING_0);
                })
                .subscribe();
    }
}
